package com.hsytech.baoinbao.unwaste;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.hsytech.baoinbao.R;
import com.hsytech.baoinbao.SharedPreferencesTools;
import com.hsytech.baoinbao.base.BaseActivity;
import com.hsytech.baoinbao.gsondata.GsonUtil;
import com.hsytech.baoinbao.volleytool.ApiUrls;
import com.hsytech.baoinbao.volleytool.HttpUtil;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Handler;

/**
 * Created by 123 on 2016/3/15.
 */
public class WasteUnStorageEasyOutActivity extends BaseActivity {
    private MListViewAdapter mListViewAdapter;
    private ListView listView;
    private List<HashMap<String, String>> listData;
    private EditText phone;
    private LinearLayout yes, no;
    private TextView area_nameText, recycling_nameText;

    private AlertDialog builderSuccess, builderPhone;
    private android.os.Handler handler = new android.os.Handler();
    private Intent intent;
    private HttpUtil.HttpCallback httpCallbackSuccess = new HttpUtil.HttpCallback() {
        @Override
        public void onSuccess(int what, JSONObject response) {
            Log.d("mylog", "onSuccess" + response);
            showDialogSuccess();

            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    builderSuccess.dismiss();
                    WasteUnStorageEasyOutActivity.this.finish();
                }
            }, 2000);

        }

        @Override
        public void onError(int what, int type, VolleyError error) {
            showToast(R.string.msg_http_failure);
        }

        @Override
        public void onErrorMsg(int what, String msg) {
            showToast(msg);
        }
    };
    private HttpUtil.HttpCallback httpCallbackChange = new HttpUtil.HttpCallback() {
        @Override
        public void onSuccess(int what, JSONObject response) {
            Log.d("mylog", "onSuccess");
            showToast("修改成功！");
            builderPhone.dismiss();
//            Map<String, String> data = new HashMap<>();
//            data.put("token", SharedPreferencesTools.getTOKEN(WasteUnStorageListDetailActivity.this));
//            HttpUtil.httpGetWithParams(0, ApiUrls.GOODS_ORDER_DETAILS + "?" + "token=" + SharedPreferencesTools.getTOKEN(WasteUnStorageListDetailActivity.this) + "&" + "id" + "=" + order_id, data, httpCallback, WasteUnStorageListDetailActivity.this);
            JSONObject result = response.optJSONObject("result");
            recycling_man_id = result.optString("id");
            recycling_man_name = result.optString("name");
            recycling_nameText.setText(recycling_man_name);
        }

        @Override
        public void onError(int what, int type, VolleyError error) {
            showToast(R.string.msg_http_failure);
        }

        @Override
        public void onErrorMsg(int what, String msg) {
            showToast(msg);
        }
    };

    private String recycling_man_id;
    private String recycling_man_name;
    private String order_ids;
    private HttpUtil.HttpCallback httpCallback = new HttpUtil.HttpCallback() {
        @Override
        public void onSuccess(int what, JSONObject response) {
            JSONObject result = response.optJSONObject("result");
            JSONArray list = result.optJSONArray("data");
            recycling_man_id = result.optString("recycling_man_id");
            recycling_man_name = result.optString("recycling_man_name");
            order_ids = result.optString("order_ids");
            Log.d("mylog", result.toString());
            for (int i = 0; i < list.length(); i++) {
                String goods_id = list.optJSONObject(i).optString("goods_id");
                int total_qty = list.optJSONObject(i).optInt("total_qty");

                all_qty = total_qty + all_qty;

                String name = list.optJSONObject(i).optString("name");

                HashMap<String, String> hashMap = new HashMap<>();
                hashMap.put("goods_id", goods_id);
                hashMap.put("total_qty", String.valueOf(total_qty));
                hashMap.put("name", name);
                listData.add(hashMap);

            }
            recycling_nameText.setText(recycling_man_name);
            mListViewAdapter.notifyDataSetChanged();


        }

        @Override
        public void onError(int what, int type, VolleyError error) {
            showToast(R.string.msg_http_failure);
        }

        @Override
        public void onErrorMsg(int what, String msg) {
            showToast(msg);
        }
    };
    private String area_id, area_name;
    private int all_qty = 0;
    private LinearLayout change;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_one_out_storage);
        setCenterTitleText("商城订单");
        setRightBtn(true);
        listView = F(R.id.list_view);
        area_nameText = F(R.id.area_name);
        recycling_nameText = F(R.id.name);
        change = F(R.id.change);

        intent = getIntent();
        area_id = intent.getStringExtra("area_id");
        area_name = intent.getStringExtra("area_name");
        area_nameText.setText(area_name);

        listData = new ArrayList<>();
        Map<String, String> data = new HashMap<>();
        data.put("token", SharedPreferencesTools.getTOKEN(WasteUnStorageEasyOutActivity.this));
        HttpUtil.httpGetWithParams(0, ApiUrls.GOODS_ORDER_LIST + "?" + "token=" + SharedPreferencesTools.getTOKEN(WasteUnStorageEasyOutActivity.this) + "&" + "area_id" + "=" + area_id, data, httpCallback, WasteUnStorageEasyOutActivity.this);

        mListViewAdapter = new MListViewAdapter(this, listData);
        listView.setAdapter(mListViewAdapter);

        change.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showPhoneDialog();
            }
        });
    }

    public void showPhoneDialog() {
        builderPhone = new AlertDialog.Builder(WasteUnStorageEasyOutActivity.this).create();
        LayoutInflater inflater = LayoutInflater.from(this);
        //获取相关的布局
        View layout = inflater.inflate(R.layout.dialog3, (ViewGroup) findViewById(R.id.dialog_parent));
        ImageView dialog_cancel = (ImageView) layout.findViewById(R.id.dialog_cancel);
        LinearLayout home_next = (LinearLayout) layout.findViewById(R.id.home_next);

//        builder.setView(layout);
        builderPhone.show();
        builderPhone.setCancelable(false);
        builderPhone.getWindow().setContentView(layout);
        phone = (EditText) layout.findViewById(R.id.phone);
        phone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        builderPhone.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
        home_next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!isEmpty(phone.getText().toString())) {

                    Map<String, String> data = new HashMap<>();

                    HttpUtil.httpGetWithParams(0, ApiUrls.CHANGE_RECYCLING + "?token=" + SharedPreferencesTools.getTOKEN(WasteUnStorageEasyOutActivity.this) +
                                    "&user_name=" + phone.getText().toString(), data,
                            httpCallbackChange, WasteUnStorageEasyOutActivity.this);

                } else {
                    showToast("请填写手机号");
                }


            }
        });
        dialog_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                builderPhone.dismiss();
            }
        });
        //只用下面这一行弹出对话框时需要点击输入框才能弹出软键盘
//        alert_leaveMsg.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
//加上下面这一行弹出对话框时软键盘随之弹出
//        alert_leaveMsg.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
    }

    private class MListViewAdapter extends BaseAdapter {

        private Context context;
        private List<HashMap<String, String>> listdata;
        private LayoutInflater inflater;

        public MListViewAdapter(Context context, List<HashMap<String, String>> listdata) {
            this.context = context;
            inflater = LayoutInflater.from(context);
            this.listdata = listdata;
        }

        @Override
        public int getCount() {
            return listdata.size();
        }

        @Override
        public Object getItem(int position) {
            return listdata.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View itemView, ViewGroup parent) {

            itemView = inflater.inflate(R.layout.item_detail_un_waste_one_out_list, null);
            TextView count = (TextView) itemView.findViewById(R.id.count);
            TextView name = (TextView) itemView.findViewById(R.id.name);

            HashMap<String, String> map = listdata.get(position);
            count.setText(map.get("total_qty"));
            name.setText(map.get("name"));
            return itemView;
        }
    }


    public void showDialog() {
        final AlertDialog builder = new AlertDialog.Builder(WasteUnStorageEasyOutActivity.this).create();
        LayoutInflater inflater = LayoutInflater.from(this);
        //获取相关的布局
        View layout = inflater.inflate(R.layout.dialog_easy_out, (ViewGroup) findViewById(R.id.dialog_parent));
        TextView name = (TextView) layout.findViewById(R.id.name);
        TextView total_price = (TextView) layout.findViewById(R.id.total_price);
        name.setText("是否确认出库?");
        total_price.setText("总数量 " + String.valueOf(all_qty));
//        builder.setView(layout);
        builder.show();
        builder.setCancelable(false);
        builder.getWindow().setContentView(layout);
        yes = (LinearLayout) layout.findViewById(R.id.yes);
        no = (LinearLayout) layout.findViewById(R.id.no);
        yes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                builder.dismiss();

                Map<String, String> data = new HashMap<>();
                data.put("token", SharedPreferencesTools.getTOKEN(WasteUnStorageEasyOutActivity.this));
                data.put("order_ids", order_ids);
                data.put("recycling_man_id", recycling_man_id);
                Log.d("mylog", " order_ids" + order_ids);
                Log.d("mylog", " recycling_man_id" + recycling_man_id);
                HttpUtil.httpPostWithParams(0, ApiUrls.DELIVER_GOODS_ALL, data, httpCallbackSuccess, WasteUnStorageEasyOutActivity.this);


            }
        });
        no.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                builder.dismiss();
            }
        });

    }

    public void showDialogSuccess() {
        builderSuccess = new AlertDialog.Builder(WasteUnStorageEasyOutActivity.this).create();
        LayoutInflater inflater = LayoutInflater.from(this);
        //获取相关的布局
        View layout = inflater.inflate(R.layout.dialog2, (ViewGroup) findViewById(R.id.dialog_parent));
        TextView name = (TextView) layout.findViewById(R.id.name);
        name.setText("出库成功!");
//        builder.setView(layout);
        builderSuccess.show();
        builderSuccess.setCancelable(false);
        builderSuccess.getWindow().setContentView(layout);
    }

    @Override
    public void onMenuRightBtn() {
        super.onMenuRightBtn();
        showDialog();
    }
}
